package com.lagou.filter;

import com.lagou.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Fxz
 * @version 1.0
 * @date 2021-10-04 21:56
 */
@Slf4j
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "Authorization";

    /**
     * 请求时会将token放到请求头中
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //如果用户访问的登录 放行
        if (request.getURI().getPath().contains("/admin/login")) {
            log.info("登录请求 放行.....");
            return chain.filter(exchange);
        }
        //获取请求头中的令牌
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        //如果用户没有携带token 错误提示
        if (StringUtils.isEmpty(token)) {
            log.info("用户没有携带token...");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //解析失败
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            log.info("jwt解析失败!");
            e.printStackTrace();
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
